<template>
    <Card dis-hover :bordered="false">
        <jg-Search
            :searchData="searchData"
            @click="guideopenedit"
            @on-enter-input="askDatakeyword"
            @on-clear-input="askDatakeyword"
            @on-change-change="askDatanow"
            @on-change-date="askDataing"
        ></jg-Search>
        <div class="i-table-no-border">
            <Table
                highlight-row
                ref="table"
                :columns="columns"
                :loading="loading"
                :data="data"
            >
                <template slot="basic" slot-scope="{ row }">
                    <span
                    ><Icon
                        style="color: #19be6b;"
                        v-if="+row.is_guide_create === 1"
                        type="ios-body"
                    />
                        {{ row.user_name }} {{ row.gender_str }}
                        {{ row.age }}岁</span
                        >
                </template>
                <template slot="mobile" slot-scope="{ row }">
                    <div v-for="(item, index) of row.mobile" :key="index">
                        <p>{{ item }}</p>
                    </div>
                </template>
                <template slot="disease" slot-scope="{ row }">
                    <span>{{
                        row.child_diseases_name || row.diseases_name
                    }}</span>
                </template>
                <template slot="status_name" slot-scope="{ row }">
                    <Badge
                        v-if="row.status_name === '到诊'"
                        status="success"
                        :text="row.status_name"
                    />
                    <Badge
                        v-else-if="row.status_name === '预约'"
                        status="processing"
                        :text="row.status_name"
                    />
                    <Badge
                        v-else-if="row.status_name === '跟进中'"
                        status="warning"
                        :text="row.status_name"
                    />
                    <Badge
                        v-else-if="row.status_name"
                        status="default"
                        :text="row.status_name"
                    />
                </template>
                <template slot-scope="{ row }" slot="info">
                    <a
                        v-hasC="{
                            name: 'patient-index-arrive',
                            flag: 'v1/patient/index/arrive',
                        }"
                        v-if="+row.op_type === 1"
                        @click="handleOpenDrawer(row)"
                    >到诊</a
                    >
                    <a
                        v-hasC="{
                            name: 'patient-index-cancel-arrive2',
                            flag: 'v1/patient/index/cancel-arrive',
                        }"
                        v-else-if="+row.op_type === 2"
                        @click="handleRemove(row)"
                        style="color: #ff9900;"
                    >撤诊</a
                    >
                    <a
                        v-hasC="{
                            name: 'v1-patient-index-guide-del',
                            flag: 'v1/patient/index/guide-del',
                        }"
                        v-else-if="+row.op_type === 0"
                        @click="handleRemoves(row)"
                    >
                        <font color="#ed4014">删除</font>
                    </a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page
                    show-total
                    show-elevator
                    show-sizer
                    :total="total"
                    :current.sync="params.page"
                    :page-size="params.pageSize"
                    :page-size-opts="pageOpts"
                    @on-change="changepage"
                    @on-page-size-change="changepageSize"
                />
            </div>
            <Modal
                v-model="modal"
                title="到诊确认"
                :mask-closable="false"
                @on-cancel="handleDrawerCancel('formItems')"
            >
                <Form
                    :model="formItems"
                    ref="formItems"
                    :label-width="100"
                    :rules="createRules"
                >
                    <FormItem label="基本信息"
                    >{{ daozhenlist.user_name }}
                        {{ daozhenlist.gender_str}}
                        {{ daozhenlist.age }}岁</FormItem
                        >
                    <FormItem label="手机号：">{{
                        daozhenlist.mobile
                    }}</FormItem>
                    <FormItem label="备注：">{{ daozhenlist.remark }}</FormItem>
                    <FormItem label="选择诊室" prop="clinic_id">
                        <Select v-model="formItems.clinic_id">
                            <Option
                                :value="item.value"
                                v-for="item in condition.clinic"
                                :key="item.value"
                            >{{ item.label }}</Option
                            >
                        </Select>
                    </FormItem>
                    <FormItem label="诊疗号" prop="patient_card_id">
                        <Input
                            v-model="formItems.patient_card_id"
                            v-width="150"
                            placeholder="请输入患者诊疗号"
                        />
                    </FormItem>
                    <FormItem label="到诊时间" prop="revisiting_time">
                        <DatePicker :editable="false"
                                    v-model="formItems.revisiting_time"
                                    :options="options"
                                    type="date"
                                    v-width="150"
                        ></DatePicker>
                    </FormItem>
                    <FormItem label="真实姓名" prop="user_name">
                        <Input
                            v-model="formItems.user_name"
                            v-width="150"
                            placeholder="请输入真实姓名"
                        />
                    </FormItem>
                    <FormItem label="居住城市">
                        <!-- <Select
                            v-model="formItems.area_code"
                            placeholder="请输入城市拼音简写"
                            filterable
                            remote
                            clearable
                            :remote-method="remoteMethod"
                            :loading="loadingcity"
                        >
                            <Option
                                v-for="item in optionscity"
                                :key="item.value"
                                :value="item.key"
                                >{{ item.label }}</Option
                            >
                        </Select> -->
                        <jgcheckcity ref="checkcity" @cityvalue="cityvalue" v-model="city_id" name="guideplan"/>
                    </FormItem>
                </Form>
                <div slot="footer">
                    <Button @click="handleDrawerCancel('formItems')"
                    >取消</Button
                    >
                    <Button
                        type="primary"
                        :loading="remarksloading"
                        @click="handleSubmit('formItems')"
                    >确定</Button
                    >
                </div>
            </Modal>
        </div>
    </Card>
</template>

<script>
import jgSearch from '@/components/search';
// import jgcheckcity from '@/components/checkcity';
import mixins from '@/mixins/mixins';
import dayjs from 'dayjs';
import {
    patientindexguidelist,
    patientindexguidecreate,
    patientindexarrive,
    patientindexcancelarrive,
    patientindexsearchcity,
    patientindexguidedel,
} from '@api/hqapi';
export default {
    /*  import引入的组件注入到components对象中使用  */
    components: { jgSearch },
    mixins: [mixins],
    data() {
        return {
            city_id: [],
            loadingcity: false,
            optionscity: [],
            remarksloading: false,
            searchData: {
                project: [
                    {
                        id: 1,
                        key: 'DatePicker',
                        style: { width: '200px' },
                        value: [new Date(), new Date()],
                        type: 'daterange',
                        options: {
                            disabledDate(date) {
                                return (
                                    date &&
                                    date.valueOf() <
                                        Date.now() - 24 * 3600 * 1000
                                );
                            },
                        },
                        callback: 'date',
                        placeholder: '请选择预到日期',
                    },
                    {
                        id: 2,
                        key: 'TreeSelect',
                        style: { width: '118px' },
                        value: '',
                        field: { value: 'value', label: 'label' },
                        childList: [],
                        clearable: 'clearable',
                        type: 'daterange',
                        callback: 'change',
                        placeholder: '请选择病种',
                    },
                    {
                        id: 3,
                        key: 'Input',
                        style: { width: '260px' },
                        value: '',
                        placeholder: '请输入患者姓名/手机号/微信号',
                        clearable: true,
                        callback: 'input',
                    },
                ],
            },
            modal: false,
            options: {
                disabledDate(date) {
                    return (
                        date && date.valueOf() < Date.now() - 24 * 3600 * 1000
                    );
                },
            },
            data: [], // 列表数据
            createRules: {
                user_name: [
                    {
                        required: true,
                        message: '请输入患者姓名',
                        trigger: 'blur',
                    },
                ],
                gender: [
                    {
                        required: true,
                        message: '请选择性别',
                        trigger: 'change',
                    },
                ],
                clinic_id: [
                    {
                        required: true,
                        message: '请选择诊室',
                        trigger: 'change',
                    },
                ],
                patient_card_id: [
                    {
                        required: true,
                        message: '请输入患者诊疗号',
                        trigger: 'blur',
                    },
                ],
                revisiting_time: [
                    {
                        required: true,
                        type: 'date',
                        message: '请输入到诊时间',
                        trigger: 'change',
                    },
                ],
            },
            /** *********************/
            year: '',
            options: {
                disabledDate(date) {
                    return date && date.valueOf() > Date.now();
                },
            },
            params: {
                page: 1,
                pageSize: 10,
                patient_diseases_id: '',
                keywords: '',
                appointment_stime: new Date(),
                appointment_etime: new Date(),
            },
            columns: [
                { title: '基本信息', slot: 'basic', width: 150, fixed: 'left' },
                {
                    title: '预到时间',
                    key: 'appointment_time_str',
                    minWidth: 138,
                },
                { title: '电话', key: 'mobile', slot: 'mobile', minWidth: 138 },
                { title: '城市', key: 'city_name', minWidth: 100 },
                { title: '病种', slot: 'disease', minWidth: 138 },
                { title: '部门', key: 'department_name', minWidth: 138 },
                { title: '一级渠道', key: 'source_name', minWidth: 138 },
                { title: '二级渠道', key: 'child_source_name', minWidth: 138 },
                { title: '创建日期', key: 'created_at_str', minWidth: 200 },
                // {
                //     title: "状态",
                //     key: "status_name",
                //     slot: "status_name",
                //     minWidth: 100,
                // }, // , slot: 'status'
                { title: '操作', slot: 'info', width: 138 },
            ], // 列表表头
            formItem: {
                user_name: '',
                gender: '',
                birthday: '',
                age: null,
                channel_id: '',
                area_code: '',
                clinic_id: '',
                patient_card_id: '',
                remark: '',
            },
            formItems: {
                id: undefined,
                user_name: '',
                area_code: '',
                clinic_id: '',
                patient_card_id: '',
                revisiting_time: new Date(),
            },
            daozhenlist: {},
            condition: {
                diseases: [],
                clinic: [],
                source_channel: [],
            },
            default_city: [
                {
                    key: '',
                    value: '',
                    label: '',
                },
            ],
        };
    },
    /* 函数方法集合 */
    methods: {
        /* @函数功能: 初始化 */
        cityvalue(city) {
            this.city_id = city;
            this.formItems.city_id = city.join(',');
            // this.askData();
        },
        initial() {
            this.funaskData = patientindexguidelist;
            this.funcreate = patientindexguidecreate;
        },
        initials(){
            this.askData();
        },
        /* @函数功能: 请求数据 */
        askDatas(res) {
            this.condition = res.condition;
            this.data = res.list;
            this.total = res.total;
            this.default_city[0].key = res.default_city.area_code;
            this.default_city[0].value = res.default_city.area_code;
            this.default_city[0].label = res.default_city.city_name;
            this.searchData.project.forEach((item) => {
                if (item.id === 2) {
                    if (item.childList.length === 0)
                        item.childList = this.condition.diseases;
                }
            });
        },
        guideopenedit() {
            this.optionscity = JSON.parse(JSON.stringify(this.default_city));
            this.openedit(-1);
        },
        remoteMethod(query) {
            if (query !== '') {
                if (parseFloat(query).toString() !== 'NaN')
                    query = query.slice(6, query.length);
                this.loadingcity = true;
                return new Promise((resolve) => {
                    setTimeout(() => {
                        patientindexsearchcity({
                            keywords: query,
                        }).then((res) => {
                            if (res.list && res.list.length > 0) {
                                const list = res.list.map((item) => {
                                    return {
                                        key: `${item.value} ${query}`,
                                        value: item.value,
                                        label: item.label,
                                    };
                                });
                                this.optionscity = list;
                            }
                            resolve(res.data);
                        });
                        this.loadingcity = false;
                    }, 200);
                });
            } else {
                this.optionscity = [];
            }
        },
        askDatakeyword() {
            this.params.page = 1;
            this.searchData.project.forEach((item) => {
                if (item.id === 3) {
                    this.params.keywords = item.value;
                } else if (item.id === 1) {
                    let keywording = '';
                      this.searchData.project.forEach(items => {
                        if (items.id === 3) {
                            keywording = items.value;
                        }
                    });
                    if (keywording !== '') {
                        if (JSON.stringify(item.value) !== JSON.stringify(['', ''])) {
                            let timer = [dayjs(item.value[0]).format('YYYY-MM-DD'),dayjs(item.value[1]).format('YYYY-MM-DD')];
                            this.storage.set('guide',timer);
                            item.value = ['', ''];
                            this.params.appointment_stime = '';
                            this.params.appointment_etime = '';
                        }
                    } else {
                            if (JSON.stringify(this.storage.get('guide')) !== JSON.stringify(['', ''])) {
                                item.value = this.storage.get('guide');
                            }
                        this.params.appointment_stime = item.value[0];
                        this.params.appointment_etime = item.value[1];
                    }
                    // item.value = "";
                    // this.params.appointment_stime = "";
                    // this.params.appointment_etime = "";
                } else if (item.id === 2) {
                    item.value = '';
                    this.params.patient_diseases_id = '';
                }
            });
            this.askData();
        },
        askDatanow() {
            this.params.page = 1;
            this.searchData.project.forEach((item) => {
                if (item.id === 2) {
                    this.params.patient_diseases_id = item.value;
                }
            });
            this.askData();
        },
        askDataing() {
            this.searchData.project.forEach((item) => {
                if (item.id === 1) {
                    this.params.appointment_stime = item.value[0];
                    this.params.appointment_etime = item.value[1];
                    let timer = ['',''];
                    if (JSON.stringify(item.value) !== JSON.stringify(['', ''])){
                        timer = [dayjs(item.value[0]).format('YYYY-MM-DD'),dayjs(item.value[1]).format('YYYY-MM-DD')];
                    } 
                    this.storage.set('guide',timer);
                }
            });
            this.askDatanow();
        },
        /* @函数功能: 打开新增或编辑 */
        handleOpenDrawer(row) {
            let rows = JSON.parse(JSON.stringify(row));
            rows.mobile = rows.mobile.join('');
            this.daozhenlist = rows;
            this.formItems.id = row.id;
            this.formItems.city_id = `${row.province_id ? row.province_id : ''},${row.city_id ? row.city_id : ''},${row.area_id ? row.area_id : ''}`;
            this.modal = true;
        },
        handleRemove(row) {
            this.$Modal.confirm({
                title: '撤诊提醒',
                content: '是否确认撤诊',
                onOk: () => {
                    patientindexcancelarrive({ id: row.id }).then(() => {
                        this.$Message.success('撤诊成功');
                        this.askData();
                    });
                },
            });
        },
        handleRemoves(row) {
            this.$Modal.confirm({
                title: '删除提醒',
                content: '是否确认删除该条信息？',
                onOk: () => {
                    patientindexguidedel({ id: row.id }).then(() => {
                        this.$Message.success('删除成功');
                        this.askData();
                    });
                },
            });
        },
        /* @函数功能: 新增或编辑提交 */
        handleSubmit(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.remarksloading = true;
                    let config = JSON.parse(JSON.stringify(this.formItems));
                        config.revisiting_time = dayjs(config.revisiting_time).format('YYYY-MM-DD');
                    patientindexarrive(config).then(() => {
                        this.$Message.success('编辑成功');
                        this.handleDrawerCancel(name);
                        this.askData();
                        this.remarksloading = false;
                    }).catch(() => {
                        this.remarksloading = false;
                    });
                }
            });
        },
        /* @函数功能: 取消新增或编辑 */
        handleDrawerCancel(name) {
            this.city_id = [];
            this.$refs[name].resetFields();
            this.formItems = {
                id: undefined,
                user_name: '',
                area_code: '',
                clinic_id: '',
                patient_card_id: '',
                revisiting_time: new Date(),
            };
            this.optionscity = [];
            this.year = '';
            this.formItem = {
                user_name: '',
                gender: '',
                birthday: '',
                age: null,
                channel_id: '',
                area_code: '',
                clinic_id: '',
                patient_card_id: '',
                remark: '',
            };
            this.modal = false;
        },
        /* @函数功能: 清空数据 */
        paramscancel() {
            this.$refs.formItem.resetFields();
            this.formItems = {
                id: undefined,
                user_name: '',
                area_code: '',
                clinic_id: '',
                patient_card_id: '',
                revisiting_time: new Date(),
            };
            this.year = '';
            this.formItem = {
                user_name: '',
                gender: '',
                birthday: '',
                age: null,
                channel_id: '',
                area_code: '',
                clinic_id: '',
                patient_card_id: '',
                remark: '',
            };
        },
        paramssubmit() {
            let config = JSON.parse(JSON.stringify(this.formItem));
            config.area_code = config.area_code.split(' ')[0];
            return config;
        },
    },
};
</script>

<style lang="less" scoped></style>
